<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Check, Close} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

interface RoleRequest {
  id: number
  userId: number
  username: string
  requestName: string
  status: string
  createTime: string
  updateTime?: string
}

interface RoleRequestListResponse {
  current: number
  total: number
  pages: number
  size: number
  records: RoleRequest[]
}

interface RoleRequestReviewDTO {
  requestId: number        // 权限申请记录ID
  decision: string         // "approve" 或 "reject"
}

const roleRequestApi = {
  getAllRequests: (params: any) => request<RoleRequestListResponse>({
    method: 'POST',
    url: '/role/list/all',
    data: params
  }),
  reviewRequest: (data: RoleRequestReviewDTO) => request<string>({
    method: 'POST',
    url: '/role/admin/review',
    data
  })
}

const requestList = ref<RoleRequest[]>([])
const loading = ref(false)

// const titleName = '权限管理'
const searchMessage = ref({
  status: ''
})

const pageNum = ref(1)
const pageSize = ref(7)
const total = ref(0)

onMounted(() => {
  getAllRequests()
})

const getAllRequests = async () => {
  loading.value = true
  try {
    const params = {
      page: pageNum.value,
      size: pageSize.value,
      status: searchMessage.value.status
    }

    const res = await roleRequestApi.getAllRequests(params)
    requestList.value = res.data.records.map(request => ({
      ...request,
      createTime: formatDateTime(request.createTime),
      updateTime: request.updateTime ? formatDateTime(request.updateTime) : ''
    }))
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取权限申请列表失败')
  } finally {
    loading.value = false
  }
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

const handleApprove = (request: RoleRequest) => {
  ElMessageBox.confirm(`确定要批准用户 ${request.username} 的 ${request.requestName} 权限申请吗？`, '审批确认', {
    confirmButtonText: '确认批准',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  }).then(async () => {
    try {
      await roleRequestApi.reviewRequest({
        requestId: request.id,
        decision: 'approve'
      })
      ElMessage.success('权限已批准')
      getAllRequests()
    } catch (error) {
      ElMessage.error('批准失败')
    }
  }).catch(() => {
    ElMessage.info('已取消批准')
  })
}

const handleReject = (request: RoleRequest) => {
  ElMessageBox.confirm('确定要驳回该权限申请吗？', '驳回确认', {
    confirmButtonText: '确认驳回',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger',
    center: true
  }).then(async () => {
    try {
      await roleRequestApi.reviewRequest({
        requestId: request.id,
        decision: 'reject'
      })
      ElMessage.success('申请已驳回')
      getAllRequests()
    } catch (error) {
      ElMessage.error('驳回失败')
    }
  }).catch(() => {
    ElMessage.info('已取消驳回')
  })
}

const search = () => {
  pageNum.value = 1
  getAllRequests()
}

const resetSearch = () => {
  searchMessage.value = {
    status: ''
  }
  pageNum.value = 1
  getAllRequests()
}

const onSizeChange = (size: number) => {
  pageSize.value = size
  getAllRequests()
}

const onCurrentChange = (num: number) => {
  pageNum.value = num
  getAllRequests()
}

const getStatusTagType = (status: string) => {
  switch (status) {
    case '待审批':
      return 'warning'
    case '已通过':
      return 'success'
    case '已驳回':
      return 'danger'
    default:
      return 'info'
  }
}
</script>

<template>
  <el-card class="card-box">
    <div class="header">
      <h2>权限管理</h2>
    </div>

    <el-form inline class="filter-bar">
      <el-form-item label="状态:" class="filter-item">
        <el-select
          v-model="searchMessage.status"
          placeholder="选择状态"
          clearable
        >
          <el-option label="待审批" value="待审批" />
          <el-option label="已通过" value="已通过" />
          <el-option label="已驳回" value="已驳回" />
        </el-select>
      </el-form-item>
      
      <el-form-item class="filter-item action-buttons">
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="responsive-table-container">
      <table class="custom-table">
        <thead>
          <tr>
            <th>编号</th>
            <th>申请人</th>
            <th>申请角色</th>
            <th>状态</th>
            <th>申请时间</th>
            <th>处理时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in requestList" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ item.username }}</td>
            <td>{{ item.requestName }}</td>
            <td>
              <el-tag :type="getStatusTagType(item.status)">
                {{ item.status }}
              </el-tag>
            </td>
            <td>{{ item.createTime }}</td>
            <td>{{ item.updateTime }}</td>
            <td>
              <div class="action-btns">
                <el-button
                  v-if="item.status === '待审批'"
                  :icon="Check"
                  circle
                  plain
                  size="small"
                  type="success"
                  @click="handleApprove(item)"
                />
                <el-button
                  v-if="item.status === '待审批'"
                  :icon="Close"
                  circle
                  plain
                  size="small"
                  type="danger"
                  @click="handleReject(item)"
                />
                <span v-if="item.status !== '待审批'" class="no-action">-</span>
              </div>
            </td>
          </tr>
          <tr v-if="requestList.length === 0">
            <td colspan="7" class="text-center py-4">
              <el-empty description="暂无权限申请记录" />
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5, 7, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      />
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.card-box {
  width: 100%;
  max-width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  padding: 0;
  overflow: hidden;
}

.header {
  padding: 0.8rem 1.2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e6eaf0;
  background-color: #f7f9fc;
  
  h2 {
    font-weight: 600;
    font-size: 1.4rem;
    color: #333;
    user-select: none;
    margin: 0;
  }
}

.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 12px;
  align-items: center;
  background-color: #f7f9fc;
}

.filter-item {
  margin-bottom: 0 !important;
  flex: 1;
  min-width: 200px;
}

.action-buttons {
  flex: none;
  margin-left: auto;
}

.responsive-table-container {
  overflow-x: auto;
  padding: 0.8rem;
}

.custom-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 6px;
  font-size: 0.9rem;

  thead tr {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
  }

  th, td {
    padding: 8px 12px;
    text-align: left;
    vertical-align: middle;
    white-space: nowrap;
  }

  tbody tr {
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    transition: background-color 0.2s ease;

    &:hover {
      background-color: #f4f9ff;
    }
  }

  .action-btns {
    display: flex;
    gap: 0.4rem;

    .el-button {
      padding: 0;
      width: 28px;
      height: 28px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
    }

    .el-button--success:hover {
      background-color: #f0f9eb;
      border-color: #e1f3d8;
      color: #67c23a;
    }

    .el-button--danger:hover {
      background-color: #fef0f0;
      border-color: #fbc4c4;
      color: #f56c6c;
    }
  }

  .no-action {
    color: #a9abb0;
    font-style: italic;
    font-size: 0.85rem;
  }
}

.pagination-container {
  padding: 0.8rem;
  display: flex;
  justify-content: center;
}

.text-center {
  text-align: center;
}

.py-4 {
  padding-top: 1rem;
  padding-bottom: 1rem;
}

@media (max-width: 768px) {
  .filter-item {
    min-width: 100%;
  }
  
  .action-buttons {
    margin-left: 0;
    width: 100%;
    display: flex;
    justify-content: flex-end;
    gap: 8px;
  }
}
</style>